var http=require('http');
var url=require('url');
var ejs=require('ejs');
//导入querystring模块（解析post请求数据）
var querystring = require('querystring');

var router=require('./model/router.js');
http.createServer(function(req,res){
    // router.statics(req,res,'./07getpost/static');

    res.writeHead(200,{'Type-Content':'text/html;charset=utf-8;'});

    var pathname=url.parse(req.url).pathname;
    var list=['111','222','333','444'];
    var data="这是后台返回的数据哦";
    if(pathname=='/login'){
        ejs.renderFile('./07getpost/views/login.ejs',{
            msg:data,
            list:list
        },function(err,data){
            res.end(data);
        });
        //res.end('login');
    } else if (pathname=='/register'){
        var data="这是注册页面也是注册路由";
        var htmlStr="<h2>这是html标签</h2>";
        ejs.renderFile('./07getpost/views/register.ejs',{
            msg:data,
            htmlStr:htmlStr
        },function(err,data){
            res.end(data);
        });
       
    } else if(pathname=='/main'){
        if(req.method=='GET'){
            var params=url.parse(req.url,true).query;
            console.log(req.url);
            ejs.renderFile('./07getpost/views/main.ejs',{
                username:params.username,
                password:params.password,
            },function(err,data){
                res.end(data);
            });
        }else{
            var postStr='';
            req.on('data',function(chunk){
                // chunk 默认是一个二进制数据，和 data 拼接会自动 toString
                postStr+=chunk;
            });
            req.on('end',function(err,chunk){
                try{
                    postStr=JSON.parse(postStr); 
                }catch(e){
                    postStr = querystring.parse(postStr);
                    console.log(postStr);
                }
                ejs.renderFile('./07getpost/views/main.ejs',{
                    username:postStr.username,
                    password:postStr.password
                },function(err,data){
                    res.end(data);
                });
            })
           
        }
    }
    else{
        ejs.renderFile('./07getpost/views/index.ejs',{
            msg:data,
            list:list
        },function(err,data){
            res.end(data);
        });
    }

}).listen(8100);